package org.jeecg.modules.demo.outstoragedetail.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.demo.msgtemplatelist.entity.MsgTemplate;
import org.jeecg.modules.demo.msgtemplatelist.service.IMsgTemplateService;
import org.jeecg.modules.demo.outstoragedetail.entity.OutStorageDetail;
import org.jeecg.modules.demo.outstoragedetail.service.IOutStorageDetailService;
import org.jeecg.modules.demo.storageoutindetail.entity.StorageOutinDetail;
import org.jeecg.modules.demo.storageoutindetail.service.IStorageOutinDetailService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.util.HttpUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecg.modules.weixin.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description: 出库单明细表
 * @Author: jeecg-boot
 * @Date: 2022-02-13
 * @Version: V1.0
 */
@Api(tags = "出库单明细表")
@RestController
@RequestMapping("/outstoragedetail/outStorageDetail")
@Slf4j
public class OutStorageDetailController extends JeecgController<OutStorageDetail, IOutStorageDetailService> {
    @Autowired
    private IOutStorageDetailService outStorageDetailService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IStorageOutinDetailService storageOutinDetailService;
    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private IMsgTemplateService msgTemplateListService;

    /**
     * 分页列表查询
     *
     * @param outStorageDetail
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "出库单明细表-分页列表查询")
    @ApiOperation(value = "出库单明细表-分页列表查询", notes = "出库单明细表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OutStorageDetail outStorageDetail,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        QueryWrapper<OutStorageDetail> queryWrapper = QueryGenerator.initQueryWrapper(outStorageDetail, req.getParameterMap());
        Page<OutStorageDetail> page = new Page<OutStorageDetail>(pageNo, pageSize);
        IPage<OutStorageDetail> pageList = outStorageDetailService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 根据主表id查询
     *
     * @param mainId
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "根据主表id查询")
    @ApiOperation(value = "根据主表id查询", notes = "根据主表id查询")
    @GetMapping(value = "/getByMainId")
    public Result<?> getByMainId(@RequestParam(name = "mainId", defaultValue = "") String mainId,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        Page<OutStorageDetail> page = new Page<OutStorageDetail>(pageNo, pageSize);
        IPage<OutStorageDetail> pageList = outStorageDetailService.getByMainId(page, mainId);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param outStorageDetail
     * @return
     */
    @AutoLog(value = "出库单明细表-添加")
    @ApiOperation(value = "出库单明细表-添加", notes = "出库单明细表-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> add(@RequestBody OutStorageDetail outStorageDetail, HttpServletRequest req) {
        //outStorageDetailService.save(outStorageDetail);
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        outStorageDetail.setStoreId(storeId);
        outStorageDetailService.save(outStorageDetail);
        //更新库存
        CommodityManagement commodityManagement = commodityManagementService.getById(outStorageDetail.getCommodityId());
        if (commodityManagement == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回退
            return Result.error("根据commodityId沒有查到添加的商品");
        }
        int inQty = outStorageDetail.getOutQty() != null ? outStorageDetail.getOutQty() : 0;
        int inventory = ToolsUtils.getNumeric(commodityManagement.getInventory());
        if (inQty > inventory) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回退
            return Result.error(commodityManagement.getTradeName() + "出库失败，出库数量超过了商品本身库存数量");
        }
        commodityManagement.setInventory(inventory - inQty);
        if (inventory - inQty == 0) {
            commodityManagement.setStatus("2");
            // 模板消息
            try {
                StoreInfo store = storeInfoService.getById(storeId);
                if (store != null) {
                    String bossGzhOpenId = storeInfoService.getBossGzhOpenId(storeId);
                    String xcxAppId = store.getXcxAppId();
                    String xcxAppSecret = store.getXcxAppSecret();
                    if (bossGzhOpenId == null) {
                        log.info("库存不足提醒模板推送失败，老板未绑定公众号");
                    } else {
                        if (store == null) {
                            log.info("库存不足提醒模板推送失败，未查到店铺信息");
                        } else {
                            String gzhAppId = store.getGzhAppId();
                            String gzhAppSecret = store.getGzhAppSecret();
                            if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                                log.info("库存不足提醒模板推送失败，店铺未绑定公众号");
                            } else {
                                String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                                String result1 = HttpUtils.sendGet(url1);
                                JSONObject resultJson1 = JSON.parseObject(result1);
                                String errcode = resultJson1.getString("errcode");
                                if (errcode != null && !"0".equals(errcode)) {
                                    log.info("库存不足提醒模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                                } else {
                                    String accessToken = resultJson1.getString("access_token");
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                    MsgTemplate msgTemplate = msgTemplateListService.getByTitle("库存不足提醒", storeId);
                                    String templateId = msgTemplate.getTemplateId();
                                    util.inventoryInsufficientNotice(templateId, bossGzhOpenId, commodityManagement.getTradeName(), String.valueOf(commodityManagement.getInventory()), sdf.format(new Date()), xcxAppId, "", accessToken);
                                    log.info("库存不足提醒模板推送成功");
                                }
                            }
                        }
                    }
                }

            } catch (Exception e) {
                log.error("库存不足提醒模板推送失败，发生异常", e);
            }
        }
        commodityManagementService.updateById(commodityManagement);

        //更新出入库明细
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        StorageOutinDetail storageOutinDetail = new StorageOutinDetail();
        storageOutinDetail.setCommodityName(commodityManagement.getTradeName());
        storageOutinDetail.setCommodityId(commodityManagement.getId());
        storageOutinDetail.setBillNo(outStorageDetail.getBillNo());
        storageOutinDetail.setOperateType("出库操作");
        storageOutinDetail.setOutinType(outStorageDetail.getOutinType());
        storageOutinDetail.setOutinQty(inQty);
        storageOutinDetail.setRemainQty(inventory - inQty);
        storageOutinDetail.setRemark(outStorageDetail.getRemark());
        storageOutinDetail.setBillTime(new Date());
        storageOutinDetail.setOperator(sysUser.getRealname());
        storageOutinDetail.setStoreId(storeId);
        storageOutinDetailService.save(storageOutinDetail);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param outStorageDetail
     * @return
     */
    @AutoLog(value = "出库单明细表-编辑")
    @ApiOperation(value = "出库单明细表-编辑", notes = "出库单明细表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody OutStorageDetail outStorageDetail) {
        outStorageDetailService.updateById(outStorageDetail);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单明细表-通过id删除")
    @ApiOperation(value = "出库单明细表-通过id删除", notes = "出库单明细表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        outStorageDetailService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出库单明细表-批量删除")
    @ApiOperation(value = "出库单明细表-批量删除", notes = "出库单明细表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.outStorageDetailService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出库单明细表-通过id查询")
    @ApiOperation(value = "出库单明细表-通过id查询", notes = "出库单明细表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        OutStorageDetail outStorageDetail = outStorageDetailService.getById(id);
        if (outStorageDetail == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(outStorageDetail);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param outStorageDetail
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OutStorageDetail outStorageDetail) {
        return super.exportXls(request, outStorageDetail, OutStorageDetail.class, "出库单明细表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OutStorageDetail.class);
    }

}
